package com.heima.user.service.impl;

import com.aliyun.teaopenapi.models.Config;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.PhoneDTO;
import com.heima.user.service.SendAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SendAuthCodeImpl implements SendAuthCode {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResponseResult sendCode(PhoneDTO phone) {

        //检查手机格式
        String regex = "^((13[0-9])|(14[5|7|9])|(15([0-9])|(17[0-9])|(18[0-9])|(19[8|9]))\\d{8})$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone.getPhone());
        if (!matcher.matches() || phone.getPhone()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"手机号码格式错误");
        }
        //获取验证码
        String randomCode = this.getRandomCode();
        ValueOperations opsForValue = redisTemplate.opsForValue();
        Boolean hasKey = redisTemplate.hasKey("code");
        if (hasKey) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "验证码已发送请稍后重试");
        }
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = null;
        try {
            com.aliyun.dysmsapi20170525.Client client = this.createClient("LTAI5tBBQNpZsVmk78pfc9Y4", "tc522gz9dtyG8rTOxSsuy01yRHPEUr");
            sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phone.getPhone())
                    .setSignName("爱思乐社交")
                    .setTemplateCode("SMS_164595129")
                    .setTemplateParam("{\"code\":" +randomCode + "}");
            // 发送验证码到手机
            client.sendSms(sendSmsRequest);
            //将验证码存入到redis当中
            opsForValue.set(phone.getPhone()+"_code", randomCode, 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("code", randomCode);
        return ResponseResult.okResult(map);
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    /**
     * @return 返回随机生成的验证码
     */
    public String getRandomCode() {

        int TemplateParam;
        double random;
        random = Math.random();
        if (random > 0.1) {
            random = random * 10000;
        } else {
            random = random * 100000;
        }
        TemplateParam = (int) Math.floor(random);
        String coadParam = String.valueOf(TemplateParam);
        return coadParam;
    }


}
